package org.peoples.rooms;

import java.util.Date;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Set;

import org.peoples.clients.ClientPool;
import org.peoples.clients.User;
import org.red5.server.api.IClient;

public class RoomPool {
	
	private volatile static RoomPool instance;
	
	private HashMap<Integer, Room> rooms;
	private HashSet<Room> roomCache;
	private int roomCount;
	
	private RoomPool() {
		
		this.rooms = new HashMap<Integer, Room> ();
		this.roomCache = new HashSet<Room> ();
		this.roomCount = 0;
		
	}
	
	
	public Room addRoom(String name, String description, Date creationDate) {
		RoomProperties properties = new RoomProperties();
		properties.name = name;
		properties.description = description;
		properties.creationDate = creationDate;
		properties.ID = roomCount++;
		
		Room room = new Room(properties);
		boolean isAdded = false;
		if (!roomCache.contains(room)) {
			isAdded = roomCache.add(room);
			rooms.put(properties.ID, room);
		}
		
		return isAdded ? room : null;
	}
	
	public static RoomPool getInstance() {
		if (instance == null) {
			synchronized (RoomPool.class) {
				if (instance == null)
					instance = new RoomPool();
			}
		}
		
		return instance;
	}
	
	public Set<Room> getAllRooms() {
		return roomCache;
	}
	
	public Room getRoom(int ID) {
		return rooms.get(ID);
	}
	
	public void removeUser(User user) {
		ClientPool clients = ClientPool.getInstance();
		IClient client = clients.getClient(user);
		
		Iterator<Room> itr = roomCache.iterator();
		while (itr.hasNext()) {
			Room room = itr.next();
			room.removeClient(client);
		}
		
	}
	
	public boolean removeRoom(int ID) {
		Room room = rooms.remove(ID);
		return roomCache.remove(room);
	}
	
}
